<?php
class CategoriesController extends AppController {

	var $name = 'Categories';
	var $uses = array('Category');
	var $components = array('Seo');
	
	function beforeFilter() {
		parent::beforeFilter();
	}

	function admin_index() {
		$this->Category->recursive = 1;
		$this->set('categories', $this->paginate());
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this -> admin_seo();
			$this->Category->create();
			if ($this->Category->save($this->data)) {
				$this->Session->setFlash(__('CATEGORIES_SAVED_OK',true));
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash(__('CATEGORIES_SAVED_ERROR',true));
			}
		}
		$articles = $this->Category->Article->generateList();
		$this->set(compact('articles'));
	}

	function admin_edit($id = null) {
		if (!$this -> Category -> findById($id)) {
			$this->Session->setFlash(__('CATEGORIES_INVALID',true));
			$this->redirect(array('action'=>'index'), null, true);
		}
		if (!empty($this->data)) {
			$this -> admin_seo();
			if ($this->Category->save($this->data)) {
				$this->Session->setFlash(__('CATEGORIES_SAVED_OK',true));
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash(__('CATEGORIES_SAVED_ERROR',true));
			}
		} else {
			$this->data = $this->Category->read(null, $id);
		}
		$articles = $this->Category->Article->generateList();
		$this->set(compact('articles'));
	}

	function admin_delete($id = null) {
		if (!$this -> Category -> findById($id)) {
			$this->Session->setFlash(__('CATEGORIES_INVALID',true));
		}
		if ($this->Category->del($id)) {
			$this->Session->setFlash(__('CATEGORIES_DELETED_OK',true));
		}
		$this->redirect(array('action'=>'index'), null, true);
	}
	
	function admin_seo()
	{
		$this -> data['Category']['seo_link'] = $this->Seo->create($this->data['Category']['name']);
	}

	function admin_delete_categories()
	{
		if($this->Category->deleteAll(array('Category.id'=>$this->data['CategoriesDelete']))) {
			$this->Session->setFlash(__('CATEGORIES_DELETED_OK',true));
		} else {
			$this->Session->setFlash(__('CATEGORIES_DELETED_ERROR',true));
		}
		
		$this->redirect(array('action'=>'index'), null, true);
	}
	
	function index() {
		$this->Category->recursive = 2;
		$this->set('categories',$this->paginate());
	}
	
	function view($seo = null) {
		if (!$this->Category->find(array('seo_link'=>$seo))) {
			$this->Session->setFlash(__('CATEGORY_INVALID',true));
			$this->redirect(array('action'=>'index'), null, true);
		} else {
			$this->Category->recursive = 2;
			$this->paginate = array('conditions'=>'Category.seo_link="'.$seo.'"','limit'=>5);
			$category = $this->paginate();
			$url = $seo;
			$this->set(compact('category','url'));
		}
	}
}
?>